package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.Permission;
import cn.tedu.knows.portal.model.Role;
import cn.tedu.knows.portal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    /*当前类需要保存到Spring容器@Component不能少
    需要基于Spring-Security设计的方法进行登录
    实现UserDetailsService接口
    下面的方法是接口提供的,我们来实现
    方法的参数使用户在登陆表单编写的用户名
    方法的返回值是UserDetails类型,这个类型对象包含登录需要的用户名
    密码权限等
     */
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.根据用户名查询用户对象
        User user = userMapper.findUserByUsername(username);
        // 2.判断是否能够查询到用户,没有用户表示用户名不存在
        if (user == null) {
            return null;
        }
        // 3.根据用户id查询用户的所有权限
        List<Permission> permissions = userMapper
                .findUserPermissionsById(user.getId());
        //  4.将权限的集合转换为String类型,并赋值
        String[] auth = new String[permissions.size()];
        int i = 0;
        for (Permission p : permissions) {
            auth[i] = p.getName();
            i++;
        }

        //查询当前用户所有角色
        List<Role> roles = userMapper.findUserRolesById(user.getId());
        //数组扩容
        auth = Arrays.copyOf(auth,auth.length+roles.size());
        for (Role role : roles){
            auth[i++] = role.getName();
        }


        // 5.构建UserDetails对象
        UserDetails details = org.springframework.security.core.userdetails.User
                .builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auth)
                //设置当前账户是否锁定 false表示不锁定
                .accountLocked(user.getLocked()==1)
                //设置当前账户是否可用 false表示可用
                .disabled(user.getEnabled()==0)
                .build();
        // 6.返回UserDetails对象

        System.out.println(details);
        return details;

    }
}
